const http = require('../../utils/http.js');
// pages/list/list.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageid:null,
    shops:[],
    pageno:0,
    pageSize:10,
    hasMore:true,
    search:""
  },
  loadMore(){
    if(!this.data.hasMore){return}
    let {pageno,pageSize}=this.data
    const params = { _page: ++pageno, _limit: pageSize}
    return http(`categories/${this.data.pageid}/shops`, params)
      .then(res => {
        if(res.data.length!=0){
            const totalCount = parseInt(res.header['X-Total-Count']);
            const hasMore = pageno * pageSize < totalCount
            var shops = this.data.shops.concat(res.data);
            this.setData({
              shops: shops,
              pageno: pageno,
              hasMore
            })
        }else{
          this.setData({
            hasMore: false
          })
        }
      })
  },
  handleVal(e){
    this.setData({
      search: e.detail.value
    })
  },
  handleSearch(){
    if(this.data.search){
      this.setData({
        pageno:0,
        shops:[]
      })
      let { pageno, pageSize } = this.data
      const params = { _page: ++pageno, _limit: pageSize, q: this.data.search }
      return http(`categories/${this.data.pageid}/shops`, params)
        .then(res => {
            var shops = this.data.shops.concat(res.data);
            if(shops.length==0){
              this.setData({
                hasMore: false
              })
            }else{
              let pageSize=this.data.pageSize;
              let hasMore=false;
              shops.length < pageSize - 1 ? hasMore = false: hasMore = true;
              this.setData({
                shops: shops,
                pageno: pageno,
                search: "",
                hasMore: hasMore
              })
            }
        })
    }
  },
  bindblur(){
    this.setData({
      search: ""
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      pageid: options.cat
    })
    http(`categories/${options.cat}`).then(res=>{
      wx.setNavigationBarTitle({
        title: res.data.name,
      })
      this.loadMore()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      shops:[],
      pageno:0
    })
    this.loadMore().then(()=>{
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadMore()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})